package com.dirox.plugins.ao;

import java.util.ArrayList;
import java.util.List;

import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.search.SearchException;
import com.atlassian.jira.jql.builder.JqlClauseBuilder;
import com.atlassian.jira.jql.builder.JqlQueryBuilder;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.web.bean.PagerFilter;

public class HelperDAO {
	private static JiraAuthenticationContext context;
	private static SearchService searchService;
	private static ProjectManager projectManager;

	public HelperDAO(JiraAuthenticationContext context,
			SearchService searchService, ProjectManager projectManager) {
		super();
		this.context = context;
		this.searchService = searchService;
		this.projectManager = projectManager;
	}

	public static List<Issue> getIssues(User user, String projectName) {
		// final User currentUser = context.getLoggedInUser();
		JqlClauseBuilder jqlClauseBuilder = JqlQueryBuilder.newClauseBuilder();
		com.atlassian.query.Query query = jqlClauseBuilder.project(projectName)
				.buildQuery();

		PagerFilter pagerFilter = PagerFilter.getUnlimitedFilter();
		com.atlassian.jira.issue.search.SearchResults searchResults = null;
		try {
			searchResults = searchService.search(user, query, pagerFilter);
		} catch (SearchException e) {
			e.printStackTrace();
		}
		return searchResults.getIssues();
	}

	public static List<Issue> getIssues(User user) {
		List<Issue> issues = new ArrayList<Issue>();
		List<Project> projects = projectManager.getProjectObjects();
		for (Project p : projects) {
			issues.addAll(getIssues(user, p.getName()));
		}
		return issues;
	}
}
